const mysql = require('mysql2/promise')
const fs = require('fs').promises

// 数据库连接配置
const dbConfig = {
  host: 'localhost',
  port: 3306,
  user: 'root',
  password: 'hyt20040702'
}

async function testConnection() {
  let connection
  try {
    // 首先创建没有指定数据库的连接
    connection = await mysql.createConnection(dbConfig)
    console.log('MySQL连接成功！')

    // 读取初始化SQL文件
    const initSql = await fs.readFile('../src/config/init.sql', 'utf8')
    
    // 执行SQL脚本
    console.log('开始执行数据库初始化脚本...')
    const statements = initSql
      .split(';')
      .map(stmt => stmt.trim())
      .filter(stmt => stmt.length > 0)

    for (let stmt of statements) {
      try {
        await connection.query(stmt)
        console.log('执行SQL成功：', stmt.substring(0, 50) + '...')
      } catch (err) {
        console.warn('执行SQL警告：', err.message)
      }
    }
    console.log('数据库初始化完成！')

    // 切换到fresh_chain数据库
    await connection.query('USE fresh_chain')

    // 测试查询
    const [rows] = await connection.query('SELECT * FROM users')
    console.log('用户表数据：', rows)

  } catch (error) {
    console.error('错误：', error)
  } finally {
    if (connection) {
      await connection.end()
      console.log('数据库连接已关闭')
    }
  }
}

// 运行测试
testConnection() 